import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { TreeNode } from '@iux/live';

@Component({
  selector: 'app-demo11',
  templateUrl: './demo11.component.html',
  styles: [
    `
      .tree-container {
        box-sizing: content-box;
        width: 3.6rem;
        padding: 0.16rem;
        border: 0.01rem solid #d9d9d9;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class Demo11Component implements OnInit {
  data: TreeNode[];
  selection: TreeNode[];
  path = 'Documents';
  constructor(private cdr: ChangeDetectorRef) {}

  ngOnInit() {
    this.initData();
  }

  initData() {
    this.data = [
      {
        label: 'Documents',
        children: [], // 异步添加的内容
      },
      {
        label: 'Word',
        children: [
          {
            label: 'Expenses.doc',
            isLeaf: true,
          },
          {
            label: 'Resume.doc',
            isLeaf: true,
          },
        ],
      },
      {
        label: 'Pictures',
        isLeaf: true,
      },
    ];

    this.handleCheckboxStatus();
  }

  handleCheckboxStatus() {
    this.data.forEach(element => {
      if (element.label === this.path) {
        element.indeterminate = true;
        return;
      }
    });
  }

  expandedChange(node) {
    if (node.label === this.path && node.children.length === 0) {
      node.isLoading = true;
      setTimeout(() => {
        node.children.push(
          {
            label: 'Resume.doc',
            isLeaf: true,
          },
          {
            label: 'test.doc',
            isLeaf: true,
          },
          {
            label: 'Expenses.doc',
            isLeaf: true,
          }
        );
        node.isLoading = false;

        this.data = [...this.data];
        this.selection = [this.data[0].children[1]];

        this.cdr.markForCheck();
      }, 1000);
    }
  }
}
